

import React, { useState, useEffect } from 'react';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import styles from './styles.module.css';

interface SearchResult {
  id: string;
  title: string;
  description: string;
  category: string;
  type: 'article' | 'video';
  image: string;
  views: string;
  likes: string;
  comments: string;
  publishTime: string;
}

const SearchResultPage: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const [searchKeyword, setSearchKeyword] = useState('思维模型');
  const [searchInputValue, setSearchInputValue] = useState('思维模型');
  const [globalSearchValue, setGlobalSearchValue] = useState('思维模型');
  const [activeCategoryFilter, setActiveCategoryFilter] = useState('全部');
  const [activeTypeFilter, setActiveTypeFilter] = useState('全部');
  const [sortBy, setSortBy] = useState('relevance');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(12);

  // 模拟搜索结果数据
  const [searchResults] = useState<SearchResult[]>([
    {
      id: 'content1',
      title: '批判性思维：如何建立理性思考框架',
      description: '掌握批判性思维的核心方法，学会独立思考和理性判断，提升决策质量。本文详细介绍了思维模型的构建过程...',
      category: '认知提升',
      type: 'article',
      image: 'https://s.coze.cn/image/SYb9A00wmcY/',
      views: '1.2万次',
      likes: '856',
      comments: '123',
      publishTime: '2天前'
    },
    {
      id: 'content2',
      title: '第一性原理：从根本上解决问题的思维模型',
      description: '深度解析埃隆·马斯克的思维模型，学会从基本原理出发思考问题，突破传统思维的限制。',
      category: '认知提升',
      type: 'video',
      image: 'https://s.coze.cn/image/SbspklXJ83M/',
      views: '15.6万次',
      likes: '2.1千',
      comments: '345',
      publishTime: '3天前'
    },
    {
      id: 'content3',
      title: '查理·芒格的多元思维模型：如何成为更聪明的思考者',
      description: '学习查理·芒格的思维框架，掌握多种思维模型的应用方法，提升跨领域思考能力。',
      category: '认知提升',
      type: 'article',
      image: 'https://s.coze.cn/image/Zwd6F6nmBxk/',
      views: '8.9千次',
      likes: '623',
      comments: '89',
      publishTime: '1周前'
    },
    {
      id: 'content4',
      title: '运动训练中的思维模型：如何制定高效训练计划',
      description: '运用思维模型来设计科学的训练计划，提高健身效果和坚持度。',
      category: '身体健身',
      type: 'video',
      image: 'https://s.coze.cn/image/vTMQKCxWALU/',
      views: '5.6千次',
      likes: '389',
      comments: '67',
      publishTime: '4天前'
    },
    {
      id: 'content5',
      title: '费曼学习法：一种强大的思维模型应用',
      description: '费曼学习法不仅是一种学习技巧，更是一种深刻的思维模型，帮助你快速掌握新知识。',
      category: '学习能力',
      type: 'article',
      image: 'https://s.coze.cn/image/bAyfFpUUZb0/',
      views: '12.3千次',
      likes: '956',
      comments: '178',
      publishTime: '5天前'
    },
    {
      id: 'content6',
      title: '实战案例：思维模型在商业决策中的应用',
      description: '通过真实的商业案例，了解思维模型如何帮助企业做出更明智的决策。',
      category: '认知提升',
      type: 'video',
      image: 'https://s.coze.cn/image/u35UvPKnFhc/',
      views: '7.8千次',
      likes: '445',
      comments: '92',
      publishTime: '6天前'
    }
  ]);

  // 设置页面标题
  useEffect(() => {
    const originalTitle = document.title;
    document.title = '搜索结果 - 精进坊';
    return () => { document.title = originalTitle; };
  }, []);

  // 处理URL参数
  useEffect(() => {
    const keyword = searchParams.get('q');
    if (keyword) {
      const decodedKeyword = decodeURIComponent(keyword);
      setSearchKeyword(decodedKeyword);
      setSearchInputValue(decodedKeyword);
      setGlobalSearchValue(decodedKeyword);
    }
  }, [searchParams]);

  // 高亮搜索关键词
  const highlightKeyword = (text: string): React.ReactNode => {
    if (!searchKeyword) return text;
    const parts = text.split(new RegExp(`(${searchKeyword})`, 'gi'));
    return parts.map((part, index) => 
      part.toLowerCase() === searchKeyword.toLowerCase() ? (
        <span key={index} className="bg-yellow-200">{part}</span>
      ) : (
        part
      )
    );
  };

  // 执行搜索
  const handlePerformSearch = () => {
    const keyword = searchInputValue.trim();
    if (keyword) {
      navigate(`/search-result?q=${encodeURIComponent(keyword)}`);
    }
  };

  // 处理搜索框回车
  const handleSearchInputKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handlePerformSearch();
    }
  };

  // 处理全局搜索框回车
  const handleGlobalSearchKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      const keyword = globalSearchValue.trim();
      if (keyword) {
        navigate(`/search-result?q=${encodeURIComponent(keyword)}`);
      }
    }
  };

  // 处理分类筛选
  const handleCategoryFilterClick = (category: string) => {
    setActiveCategoryFilter(category);
    setCurrentPage(1); // 重置到第一页
  };

  // 处理内容类型筛选
  const handleTypeFilterClick = (type: string) => {
    setActiveTypeFilter(type);
    setCurrentPage(1); // 重置到第一页
  };

  // 处理排序变更
  const handleSortChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setSortBy(e.target.value);
    setCurrentPage(1); // 重置到第一页
  };

  // 处理搜索结果点击
  const handleResultClick = (contentId: string) => {
    navigate(`/content-detail?id=${contentId}`);
  };

  // 处理分页
  const handlePrevPage = () => {
    if (currentPage > 1) {
      setCurrentPage(currentPage - 1);
    }
  };

  const handleNextPage = () => {
    setCurrentPage(currentPage + 1);
  };

  const handlePageClick = (page: number) => {
    setCurrentPage(page);
  };

  // 处理每页显示数量变更
  const handlePageSizeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setPageSize(Number(e.target.value));
    setCurrentPage(1); // 重置到第一页
  };

  // 获取分类样式
  const getCategoryStyle = (category: string) => {
    switch (category) {
      case '认知提升':
        return 'bg-secondary text-white';
      case '身体健身':
        return 'bg-green-500 text-white';
      case '学习能力':
        return 'bg-purple-500 text-white';
      default:
        return 'bg-secondary text-white';
    }
  };

  // 获取内容类型样式
  const getTypeStyle = (type: string) => {
    return type === 'article' ? 'bg-blue-100 text-blue-600' : 'bg-red-100 text-red-600';
  };

  // 获取内容类型图标
  const getTypeIcon = (type: string) => {
    return type === 'article' ? 'fas fa-eye' : 'fas fa-play';
  };

  return (
    <div className={styles.pageWrapper}>
      {/* 顶部导航栏 */}
      <header className="fixed top-0 left-0 right-0 h-16 bg-white shadow-sm z-50">
        <div className="flex items-center justify-between h-full px-6">
          {/* Logo和产品名称 */}
          <div className="flex items-center space-x-3">
            <div className={`w-10 h-10 ${styles.gradientBg} rounded-xl flex items-center justify-center`}>
              <i className="fas fa-graduation-cap text-white text-lg"></i>
            </div>
            <h1 className="text-xl font-bold text-text-primary">精进坊</h1>
          </div>
          
          {/* 主导航 */}
          <nav className="hidden md:flex items-center space-x-8">
            <Link to="/home" className="px-4 py-2 rounded-lg text-center text-text-secondary hover:text-secondary">首页</Link>
            <Link to="/cognition-home" className="px-4 py-2 rounded-lg text-center text-text-secondary hover:text-secondary">认知提升</Link>
            <Link to="/fitness-home" className="px-4 py-2 rounded-lg text-center text-text-secondary hover:text-secondary">身体健身</Link>
            <Link to="/learning-home" className="px-4 py-2 rounded-lg text-center text-text-secondary hover:text-secondary">学习能力</Link>
          </nav>
          
          {/* 搜索框和用户操作区 */}
          <div className="flex items-center space-x-4">
            {/* 搜索框 */}
            <div className="relative hidden lg:block">
              <input 
                type="text" 
                placeholder="搜索内容..." 
                className="w-64 pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent"
                value={globalSearchValue}
                onChange={(e) => setGlobalSearchValue(e.target.value)}
                onKeyPress={handleGlobalSearchKeyPress}
              />
              <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
            </div>
            
            {/* 消息通知 */}
            <button className="relative p-2 text-gray-600 hover:text-secondary">
              <i className="fas fa-bell text-lg"></i>
              <span className="absolute -top-1 -right-1 w-3 h-3 bg-red-500 rounded-full"></span>
            </button>
            
            {/* 用户头像/昵称 */}
            <div className="relative">
              <button className="flex items-center space-x-2 p-2 rounded-lg hover:bg-gray-100">
                <img 
                  src="https://s.coze.cn/image/OKNMJy9sZN8/" 
                  alt="用户头像" 
                  className="w-8 h-8 rounded-full" 
                />
                <span className="hidden md:block text-text-primary font-medium">张三</span>
                <i className="fas fa-chevron-down text-xs text-gray-400"></i>
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* 主布局容器 */}
      <div className="flex pt-16 min-h-screen">
        {/* 左侧菜单 */}
        <aside className="w-64 bg-white shadow-sm border-r border-gray-100">
          <div className="p-6">
            <nav className="space-y-2">
              <Link to="/home" className={`${styles.sidebarItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-home text-lg"></i>
                <span>首页</span>
              </Link>
              <Link to="/cognition-home" className={`${styles.sidebarItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-brain text-lg"></i>
                <span>认知提升</span>
              </Link>
              <Link to="/fitness-home" className={`${styles.sidebarItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-dumbbell text-lg"></i>
                <span>身体健身</span>
              </Link>
              <Link to="/learning-home" className={`${styles.sidebarItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-book text-lg"></i>
                <span>学习能力</span>
              </Link>
              <Link to="/user-profile" className={`${styles.sidebarItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-user text-lg"></i>
                <span>个人中心</span>
              </Link>
              <Link to="/user-collections" className={`${styles.sidebarItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-heart text-lg"></i>
                <span>我的收藏</span>
              </Link>
              <Link to="/user-history" className={`${styles.sidebarItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-history text-lg"></i>
                <span>学习历史</span>
              </Link>
            </nav>
          </div>
        </aside>

        {/* 主内容区 */}
        <main className="flex-1 p-6">
          {/* 页面头部 */}
          <div className="mb-8">
            <div className="flex items-center justify-between">
              <div>
                <h2 className="text-2xl font-bold text-text-primary mb-2">搜索结果</h2>
                <nav className="text-sm text-text-secondary">
                  <span>首页</span>
                  <i className="fas fa-chevron-right mx-2"></i>
                  <span>搜索结果</span>
                </nav>
              </div>
              <div className="text-right">
                <div className="text-sm text-text-secondary">找到 <span className="font-medium text-secondary">127</span> 个结果</div>
                <div className="text-xs text-text-secondary">关键词："<span>{searchKeyword}</span>"</div>
              </div>
            </div>
          </div>

          {/* 搜索工具栏 */}
          <div className={`${styles.contentCard} rounded-card shadow-card p-4 mb-6`}>
            <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between space-y-4 lg:space-y-0">
              {/* 搜索框 */}
              <div className="flex-1 lg:max-w-md">
                <div className="relative">
                  <input 
                    type="text" 
                    placeholder="重新搜索..." 
                    className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-secondary focus:border-transparent"
                    value={searchInputValue}
                    onChange={(e) => setSearchInputValue(e.target.value)}
                    onKeyPress={handleSearchInputKeyPress}
                  />
                  <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                  <button 
                    className="absolute right-2 top-1/2 transform -translate-y-1/2 px-3 py-1 bg-secondary text-white rounded-md text-sm hover:bg-accent"
                    onClick={handlePerformSearch}
                  >
                    搜索
                  </button>
                </div>
              </div>

              {/* 筛选和排序 */}
              <div className="flex flex-wrap items-center gap-4">
                {/* 分类筛选 */}
                <div className="flex items-center space-x-2">
                  <span className="text-sm text-text-secondary">分类：</span>
                  <div className="flex space-x-1">
                    {['全部', '认知提升', '身体健身', '学习能力'].map((category) => (
                      <button 
                        key={category}
                        className={`px-3 py-1 text-sm rounded-md border border-gray-200 hover:border-secondary ${
                          activeCategoryFilter === category 
                            ? styles.filterActive 
                            : 'text-text-secondary'
                        }`}
                        onClick={() => handleCategoryFilterClick(category)}
                      >
                        {category}
                      </button>
                    ))}
                  </div>
                </div>

                {/* 内容类型筛选 */}
                <div className="flex items-center space-x-2">
                  <span className="text-sm text-text-secondary">类型：</span>
                  <div className="flex space-x-1">
                    {['全部', '文章', '视频'].map((type) => (
                      <button 
                        key={type}
                        className={`px-3 py-1 text-sm rounded-md border border-gray-200 hover:border-secondary ${
                          activeTypeFilter === type 
                            ? styles.filterActive 
                            : 'text-text-secondary'
                        }`}
                        onClick={() => handleTypeFilterClick(type)}
                      >
                        {type}
                      </button>
                    ))}
                  </div>
                </div>

                {/* 排序 */}
                <div className="flex items-center space-x-2">
                  <span className="text-sm text-text-secondary">排序：</span>
                  <select 
                    className="px-3 py-1 text-sm border border-gray-200 rounded-md focus:outline-none focus:ring-2 focus:ring-secondary"
                    value={sortBy}
                    onChange={handleSortChange}
                  >
                    <option value="relevance">相关性</option>
                    <option value="latest">最新发布</option>
                    <option value="popular">最热</option>
                  </select>
                </div>
              </div>
            </div>
          </div>

          {/* 搜索结果展示区 */}
          <div className="mb-8">
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {searchResults.map((result) => (
                <div 
                  key={result.id}
                  className={`${styles.contentCard} rounded-card shadow-card p-6 ${styles.cardHover} cursor-pointer`}
                  onClick={() => handleResultClick(result.id)}
                >
                  <div className="flex space-x-4">
                    <img 
                      src={result.image} 
                      alt={`${result.title}封面`} 
                      className="w-24 h-24 object-cover rounded-lg flex-shrink-0"
                    />
                    <div className="flex-1">
                      <div className="flex items-center space-x-2 mb-2">
                        <span className={`px-2 py-1 rounded-full text-xs ${getCategoryStyle(result.category)}`}>
                          {result.category}
                        </span>
                        <span className={`px-2 py-1 rounded-full text-xs ${getTypeStyle(result.type)}`}>
                          {result.type === 'article' ? '文章' : '视频'}
                        </span>
                      </div>
                      <h4 className="font-semibold text-text-primary mb-2 line-clamp-2">
                        {highlightKeyword(result.title)}
                      </h4>
                      <p className="text-text-secondary text-sm mb-3 line-clamp-2">
                        {highlightKeyword(result.description)}
                      </p>
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-4 text-xs text-text-secondary">
                          <span><i className={`${getTypeIcon(result.type)} mr-1`}></i>{result.views}</span>
                          <span><i className="fas fa-heart mr-1"></i>{result.likes}</span>
                          <span><i className="fas fa-comment mr-1"></i>{result.comments}</span>
                        </div>
                        <div className="text-xs text-text-secondary">
                          <span>{result.publishTime}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 分页区域 */}
          <div className={`${styles.contentCard} rounded-card shadow-card p-4`}>
            <div className="flex items-center justify-between">
              <div className="text-sm text-text-secondary">
                显示第 <span className="font-medium">1-12</span> 条，共 <span className="font-medium">127</span> 条结果
              </div>
              
              <div className="flex items-center space-x-2">
                <button 
                  className="px-3 py-1 text-sm border border-gray-200 rounded-md hover:border-secondary disabled:opacity-50" 
                  disabled={currentPage === 1}
                  onClick={handlePrevPage}
                >
                  <i className="fas fa-chevron-left mr-1"></i>上一页
                </button>
                
                <div className="flex space-x-1">
                  <button 
                    className={`px-3 py-1 text-sm border rounded-md ${
                      currentPage === 1 
                        ? 'border-secondary bg-secondary text-white' 
                        : 'border-gray-200 hover:border-secondary'
                    }`}
                    onClick={() => handlePageClick(1)}
                  >
                    1
                  </button>
                  <button 
                    className={`px-3 py-1 text-sm border rounded-md ${
                      currentPage === 2 
                        ? 'border-secondary bg-secondary text-white' 
                        : 'border-gray-200 hover:border-secondary'
                    }`}
                    onClick={() => handlePageClick(2)}
                  >
                    2
                  </button>
                  <button 
                    className={`px-3 py-1 text-sm border rounded-md ${
                      currentPage === 3 
                        ? 'border-secondary bg-secondary text-white' 
                        : 'border-gray-200 hover:border-secondary'
                    }`}
                    onClick={() => handlePageClick(3)}
                  >
                    3
                  </button>
                  <span className="px-3 py-1 text-sm text-text-secondary">...</span>
                  <button 
                    className={`px-3 py-1 text-sm border rounded-md ${
                      currentPage === 11 
                        ? 'border-secondary bg-secondary text-white' 
                        : 'border-gray-200 hover:border-secondary'
                    }`}
                    onClick={() => handlePageClick(11)}
                  >
                    11
                  </button>
                </div>
                
                <button 
                  className="px-3 py-1 text-sm border border-gray-200 rounded-md hover:border-secondary"
                  onClick={handleNextPage}
                >
                  下一页<i className="fas fa-chevron-right ml-1"></i>
                </button>
              </div>
              
              <div className="flex items-center space-x-2">
                <span className="text-sm text-text-secondary">每页显示</span>
                <select 
                  className="px-2 py-1 text-sm border border-gray-200 rounded focus:outline-none focus:ring-2 focus:ring-secondary"
                  value={pageSize}
                  onChange={handlePageSizeChange}
                >
                  <option value="12">12</option>
                  <option value="24">24</option>
                  <option value="48">48</option>
                </select>
                <span className="text-sm text-text-secondary">条</span>
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>
  );
};

export default SearchResultPage;

